// lib/utils/crypto_utils.dart
import 'dart:async';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

/// 计算 HMAC-SHA256，返回小写十六进制字符串（32字节 -> 64位hex）
/// [key] 用作 HMAC 的密钥（通常为密码或服务端下发的密钥）
/// [message] 要签名的消息（如一次性 nonce / 验证码）
String hmacSha256Hex({required String key, required String message}) {
  final mac = Hmac(sha256, utf8.encode(key));
  final digest = mac.convert(utf8.encode(message));
  return digest.toString(); // 小写hex
}

void toastCenter(String msg) {
  Fluttertoast.showToast(
    msg: msg,
    gravity: ToastGravity.CENTER,
    toastLength: Toast.LENGTH_SHORT,
    backgroundColor: Colors.black87,
    textColor: Colors.white,
    fontSize: 14,
  );
}

void showLoading() {
  Get.dialog(
    Center(child: CircularProgressIndicator()),
    barrierDismissible: false,
  );
}

void hideLoading() {
  Get.back();
}

enum ToastPos { top, bottom }

class AppToast {
  static OverlayEntry? _entry;
  static Timer? _timer;

  static void _remove() {
    _timer?.cancel();
    _timer = null;
    _entry?.remove();
    _entry = null;
  }

  /// 显示覆盖层 Toast（会自动关闭上一个）
  static void show(
    String msg, {
    Duration duration = const Duration(seconds: 2),
    ToastPos position = ToastPos.top,
    EdgeInsets margin = const EdgeInsets.all(12),
  }) {
    // 先关掉上一个
    if (_entry != null) _remove();

    final ctx = Get.overlayContext ?? Get.context;
    if (ctx == null) return;
    final overlay = Overlay.of(ctx, rootOverlay: true); // 顶层 overlay，盖过蒙版

    final top = MediaQuery.of(ctx).padding.top + margin.top;
    final bottom = MediaQuery.of(ctx).padding.bottom + margin.bottom;

    _entry = OverlayEntry(
      builder: (_) => Positioned(
        left: margin.left,
        right: margin.right,
        top: position == ToastPos.top ? top : null,
        bottom: position == ToastPos.bottom ? bottom : null,
        child: Material(
          color: Colors.transparent,
          child: GestureDetector(
            onTap: close, // 点一下手动关闭
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
              decoration: BoxDecoration(
                color: const Color(0xE6000000),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                msg,
                style: const TextStyle(color: Colors.white, fontSize: 14),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
      ),
    );

    overlay.insert(_entry!);
    _timer = Timer(duration, () => _remove());
  }

  /// 手动关闭
  static void close() => _remove();
}
